﻿using Microsoft.EntityFrameworkCore;

namespace HostedServiceDemo1
{
    public class ScheduledService : BackgroundService
    {
        private IServiceScope serviceScope;

        public ScheduledService(IServiceScopeFactory serviceScopeFactory)
        {
            this.serviceScope = serviceScopeFactory.CreateScope();
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                MyDbContext context = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();

                while (!stoppingToken.IsCancellationRequested)
                {
                    //每5秒写入配置项有多少
                    long count = context.t_Configs.AsNoTracking().LongCount();
                    await File.WriteAllTextAsync("d:/config.txt", count.ToString());
                    await Task.Delay(5000);
                    Console.WriteLine($"导出成功:{DateTime.Now}");
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生异常:{ex.Message}");
            }
        }

        public override void Dispose()
        {
            this.serviceScope.Dispose();
            base.Dispose();
        }
    }
}
